var express = require('express');
var session = require('express-session');
var router = express.Router();
var app = express();
//npm install body-parser --save
var bodyParser = require('body-parser');
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })

//npm install connect-multiparty --save
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();

var fs = require("fs");
//npm install path --save
var path = require('path');
//npm install multer --save
var multer  = require('multer');

var upload = multer({ dest: path.join(__dirname, '../public/upload/') });
var session = require('express-session');
// 服务端解析客户端发送过来的cookie，序列化
//npm install cookie-parser --save
const cookieParser = require('cookie-parser')

app.use(cookieParser());
//当form的multipart=form-data
router.post('/formdata',multipartMiddleware, function (req, res) {
  console.log(req.body);
  var response = {
       "first_name":req.body.first_name,
       "last_name":req.body.last_name
   };
   console.log(response);
   res.end(JSON.stringify(response));
   
});
 
//上传文件 
// 注意：1、'upload_file'  对应于 form 表单中的 name 属性值。
// 2、代码 执行完 upload.single('upload_file') 的时候，文件就已经上传了，但是没有后缀名，得改一下名称
router.post('/upload', upload.single('upload_file'), function(req, res) {
    var temp_path = req.file.path;
    var file_size = req.file.size;
	if(file_size>500*1024){
		res.end( 'File should not bigger than 500 KB!' );
	}
    var ext = '.' + req.file.originalname.split('.')[1];
    var target_path = req.file.path + ext;
    var _filename = req.file.filename + ext;
    var filePath = '/upload/' + _filename;
    console.log("Uploading: " + _filename);
    fs.rename(temp_path, target_path, function(err,data) {
     if(err){
		throw err;
	 }
	 console.log('done!');
    });
	res.end( 'File uploaded successfully' );
});

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

router.get('/index', function(req, res) {   
   console.log("/users/index GET 请求");
   res.send('users/index');
});

//读取静态文件内容
router.get('/info.htm', function (req, res) {
   res.sendFile( app.get('views') + "/" + "info.htm" );
})

//当form的multipart=application/x-www-form-urlencoded
router.post('/save', urlencodedParser, function (req, res) {
   // 输出 JSON 格式
   var response = {
       "first_name":req.body.first_name,
       "last_name":req.body.last_name
   };
   console.log(response);
   res.end(JSON.stringify(response));
})

//向客户端返回cookie
router.get('/setcookie',   function (req, res) {
   // 输出 JSON 格式
   var response = {
       "first_name":'jim',
       "last_name":'green'
   };
   console.log(response);
   res.cookie('user',JSON.stringify(response),{path:'/',maxAge:30*24*3600*1000, httpOnly: true});
   res.end(JSON.stringify(response));
})

//读取cookie
router.get('/getcookie',   function (req, res) {
   console.log(req.cookies.user);
   res.send("获取cookie成功，cookie为："+ req.cookies.user); 
})

//删除cookie
router.get('/delcookie',   function (req, res) {
   res.cookie('user', '', { expires: new Date(0)}); 	
   console.log(req.cookies.user);
   res.send("删除cookie成功！"); 
})

router.get('/login', function (req, res) {
    
    // if (!req.session.user) req.session.user = req.body;
    if (!req.session.user) req.session.user = {"username":"uuuu","password":"123456"};
    req.session.auth = true;
    res.setHeader('Content-Type', 'text/html');
    res.write('session:' + JSON.stringify(req.session));
    res.write('expires:'+ JSON.stringify(req.session.cookie.maxAge/1000));
    console.log('post: ' + req.session.id);//加上一句
    /**
    使用x-www-form-urlencoded的表单头发送post信息username=uuuu&password=123456
    session:{"cookie":{"originalMaxAge":180000,"expires":"2019-12-03T17:01:02.822Z","httpOnly":true,"path":"/"},"user":{"username":"uuuu","password":"123456"}}
    expires:180
    */
    res.end();
});
//读取静态文件内容
router.get('/sessioninfo', function (req, res) {
   res.send("获取session成功，session为："+JSON.stringify(req.session.user)); 
});

router.get('/logout', (req, res, next) => {
 if (req.session) {
  req.session.destroy() // 删除session
  res.clearCookie('session-id') // 删除cookie
  res.send('登出成功。重定向的事让前端做')
 } else {
  var err = new Error('you are not logged in!')
  err.status = 403
  next(err)
 }
})
module.exports = router;
